package com.sgb.kjwl.viewmodel.pick;

import android.content.Intent;
import android.util.Log;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;




import com.sgb.kjwl.api.APIManager;

import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.link.utils.Preferences;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.PickServiceTypeEntity;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.model.entity.user.PickCompanyListEntity;
import com.sgb.kjwl.repository.PickRepertory;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.kjwl.view.ui.fragment.pick.PickCompanyListFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PickCompanyModel extends BaseViewModel {
    private PickCompanyListFragment pickCompanyListFragment;
    private PickRepertory repertory;
    private HashMap map;
    private PickSelectEntity mAll;

    public PickCompanyModel(PickCompanyListFragment pickCompanyListFragment, PickRepertory repertory) {
        this.pickCompanyListFragment = pickCompanyListFragment;
        this.repertory = repertory;
        mAll = new PickSelectEntity();
        mAll.setNo("");
        mAll.setProjectscale("全部");
    }

    public void findTenderEnterprisePage(String searchName,String model,String type,String cityNo,String areaCode, int total, int page) {
        map = new HashMap();
//        map.put("areacode", repertory.getAreaCode());
//        map.put("keyword", searchName);
//        map.put("limit", 10);
//        map.put("page", page);
//        map.put("total", total);
//        DialogHelper.showProgressDialog2(pickCompanyListFragment.getContext(), null, "加载中", 0, true, null);
//        APIManager.getInstance().getPickAPI().findTenderEnterprisePage(map).enqueue(new ICallBack<BaseEntity<PickSearchTender<List<PickCompanyListEntity>>>>() {
//            @Override
//            public void onSuccess(BaseEntity<PickSearchTender<List<PickCompanyListEntity>>> data) {
//                if (data == null || data.getState() == null)
//                    return;
//                if (data.getData().getList() == null){
//                    data.getData().setList(new ArrayList<>());
//                }
//                if (page == 1){
//                    pickCompanyListFragment.showData(data.getData().getList());
//                }else{
//                    pickCompanyListFragment.showMoreData(data.getData().getList());
//                }
//            }
//
//            @Override
//            public void onFail() {
//                super.onFail();
//                pickCompanyListFragment.emptyView();
//            }
//        });

        if (!"".equals(areaCode) && areaCode != null)
            map.put("province", areaCode);
        if (!"".equals(cityNo) && cityNo != null)
            map.put("city", cityNo);
        if (!"".equals(type) && type != null)
            map.put("serviceType", type);
        if (!"".equals(model) && model != null)
            map.put("scope", model);
        if (!"".equals(searchName) && searchName != null)
            map.put("searchName", searchName);
        map.put("limit",10);
        map.put("page", page);

        DialogHelper.showProgressDialog2(pickCompanyListFragment.getContext(), null, "数据加载中...", 0, false, null,false);
        APIManager.getInstance().getPickAPI().findTenderCompanyList(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<PickCompanyListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<PickCompanyListEntity>>> data) {

                if (data != null && data.getData() != null) {
                    if (page == 1){
                        pickCompanyListFragment.showData(data.getData().getList());
                    }else{
                        pickCompanyListFragment.showMoreData(data.getData().getList());
                    }
                }

            }
        });
    }

    public void getProvinceData() {
        DialogHelper.showProgressDialog2(pickCompanyListFragment.getContext(), null, "加载中", 0, true, null,false);
        APIManager.getInstance().getPickAPI().getAddressEntityCityList().enqueue(new ICallBack<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> data) {
                if (data != null && data.getData() != null && data.getData().size() > 0) {
                    pickCompanyListFragment.setProvinceDatas(data.getData());
                }
            }
        });
    }

    public void getAddressCityData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData, String no) {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> scrDatum : scrData) {
            if (scrDatum.getId().equals(no)) {
                List<AddressEntity<List<AddressEntity>>> children = scrDatum.getChildren();
                if (children != null && children.size() > 0) {
                    List<PickSelectEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity>> child : children) {
                        entities.add(new PickSelectEntity(child.getNo(), child.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    pickCompanyListFragment.setCityDatas(entities);
                }
            }
        }
    }

    public void getSelecteScaleData(){
        Map<String, Integer> map = new HashMap<>();
        map.put("type", 0);
        APIManager.getInstance().getPickAPI().getProjectScale3(map).enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null){
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)){
                    if (response.body().getData() != null) {
                        pickCompanyListFragment.setScaleDatas(response.body().getData());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                Log.e("api",t.toString());
            }
        });
    }

    public void getServiceTypeList() {
        Map map = new HashMap();
        DialogHelper.showProgressDialog2(pickCompanyListFragment.getContext(), null, "数据加载中...", 0, false, null,false);
        APIManager.getInstance().getPickAPI().getServiceTypeList(map).enqueue(new Callback<BaseEntity<List<PickServiceTypeEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickServiceTypeEntity>>> call, Response<BaseEntity<List<PickServiceTypeEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<PickServiceTypeEntity> data = response.body().getData();
                    List<PickSelectEntity> typeDatas = new ArrayList<>();
                    for(PickServiceTypeEntity pickServiceTypeEntity :data){
                        typeDatas.add(new PickSelectEntity(pickServiceTypeEntity.getCode(),pickServiceTypeEntity.getName()));
                    }
                    pickCompanyListFragment.setTypeDatas(typeDatas);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickServiceTypeEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void userFocus(String businessNo, boolean isGz, int position) {
        if (map == null)
            map = new HashMap();
        map.put("businessNo", businessNo);
        map.put("type", 0);
        DialogHelper.showProgressDialog2(pickCompanyListFragment.getContext(), null, "请求中...", 0, false, null,false);
        APIManager.getInstance().getPickAPI().userFocus(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    pickCompanyListFragment.setIsGz(isGz,position);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog2(pickCompanyListFragment.getContext(), null, "登录中", 0, false, null,false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(pickCompanyListFragment.getContext(), SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        pickCompanyListFragment.startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                DialogHelper.dismissProgressDialog();
                SharedPreferenceUtil.getInstance().cleatData();
                saveUserInfo(response.body().getData());
                MToast.showToast(pickCompanyListFragment.getContext(), "登录成功");
                pickCompanyListFragment.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                JPushInterface.setAlias(pickCompanyListFragment.getContext(), 1, response.body().getData().getPhone());
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog2(pickCompanyListFragment.getContext(), null, "请求中...", 0, false, null,false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    pickCompanyListFragment.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(pickCompanyListFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
